package com.qianya.system.face.web.patient.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.qianya.model.common.ResultCode;
import com.qianya.model.pojo.patient.qo.ImageObj;
import com.qianya.system.face.web.patient.faceutil.dto.FaceRecognitionResDTO;
import com.qianya.system.face.web.patient.model.PatientFileInfo;
import com.qianya.system.face.web.patient.service.FaceEngineService;
import com.qianya.model.common.CommonResult;
import com.qianya.system.face.web.patient.service.IPatientFileInfoService;
import com.qianya.util.SystemConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/patient/face")
@Api(value = "FaceController", tags = "人脸识别接口")
@Slf4j
@Validated
/**
 * @desc
 * @author lhl
 * @date 2020-08-06 10:40
 * @return
 */
public class FaceController {

    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private IPatientFileInfoService patientFileInfoService;

    /**
     * @return
     * @desc 人脸添加
     * @author lhl
     * @date 2020-07-01 17:35
     */
   /* @ApiOperation("人脸添加")
    @PostMapping(value = "/faceAdd")
    public CommonResult faceAdd(@RequestBody PatientFileInfoAddQO fileInfoQq) {
        PatientFileInfo fileInfo = new PatientFileInfo();
        BeanUtils.copyProperties(fileInfoQq,fileInfo);
        return  faceEngineService.faceAdd(fileInfo);
    }*/
    /*
    人脸识别
     */
    @ApiOperation("人脸比对")
    @PostMapping(value = "/faceRecognition")
    public CommonResult<FaceRecognitionResDTO> faceRecognition(@Valid @RequestBody ImageObj image) {
        return faceEngineService.faceRecognition(image.getImage());
    }

    @ApiOperation("根据人员身份证号或者his号或手机号查询医嘱")
    @GetMapping(value = "/selectPatientAdvice")
    public CommonResult<FaceRecognitionResDTO> selectPatientAdvice(@ApiParam(value = "（ID）身份证号或his住院号或手机号", required = true)
                                                                   @NotBlank(message = "ID不能为空")
                                                                   @RequestParam(defaultValue = "", name = "id") String id) {
        return faceEngineService.selectPatientAdvice(id);
    }

    @ApiOperation("人脸数据导入")
    @PostMapping(value = "/fileUpload")
    public CommonResult fileUpload(MultipartFile multipartFile) {
        String fileType = "";
        ExcelReader reader = null;
        try {
            String fileName = multipartFile.getOriginalFilename();
            fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
                    fileName.lastIndexOf(".") + 4);
            if (!fileType.toLowerCase().equals("xls")) {
                return CommonResult.error(ResultCode.OTHER_EXCEPTION, "导入的文件格式不正确，只能是.xls或.xlsx后缀的文件");
            }
            reader = ExcelUtil.getReader(multipartFile.getInputStream());
            List<List<Object>> readAll = reader.read();
            /*根据身份证判断是否重复添加*/
            List<PatientFileInfo> oldList = patientFileInfoService.list();
            Map<String, Integer> map = new HashMap<>();
            for (int i = 0; i < oldList.size(); i++) {
                map.put(oldList.get(i).getFilePatientIdNum(), 1);
            }
            /*根据身份证判断是否重复添加*/
            List<PatientFileInfo> list = new ArrayList<>();
            PatientFileInfo pfi = null;
            String uuid = UUID.randomUUID().toString();
            for (int i = 1; i < readAll.size(); i++) {
                pfi = new PatientFileInfo();
                pfi.setFilePatientIdNum(readAll.get(i).get(5).toString());
                if (map.get(pfi.getFilePatientIdNum()) != null) {
                    continue;  //已存在的身份证号，自动过滤
                }
                pfi.setFileHospitalNum(readAll.get(i).get(0).toString());
                pfi.setFilePatientName(readAll.get(i).get(1).toString());
                pfi.setFilePatientGender(readAll.get(i).get(2).toString().equals("男") ? 1 : 0);
                pfi.setFilePatientAge(Integer.valueOf(readAll.get(i).get(3).toString()));

                File file = QrCodeUtil.generate(readAll.get(i).get(5).toString(), 300, 300, FileUtil.file(SystemConfig.filePath() + "qrcode\\" + uuid + ".jpg"));
                String QrCodePath = file.getAbsolutePath();
                String replace = QrCodePath.replace( QrCodePath,"\\statics\\qrcode" +File.separator+ uuid + ".jpg");
                pfi.setFileQrcode(replace);
                pfi.setFilePatientTel(readAll.get(i).get(4).toString());
                pfi.setFilePatientResidence(readAll.get(i).get(6).toString());
                pfi.setFilePatientIcon("/statics/image/default.jpg");
                pfi.setFileAdmissionDate(new Date());
                list.add(pfi);
                if (list.size() == 1000) {
                    patientFileInfoService.saveBatch(list);
                    list.clear();
                }
            }
            if (list.size() != 0) {
                patientFileInfoService.saveBatch(list);
            }
            return CommonResult.success();
        } catch (IOException e) {
            return CommonResult.error(ResultCode.ERROR, "导入失败，请按照模板格式上传");
        } catch (Exception e) {
            return CommonResult.error(ResultCode.ERROR, "请上传正确的模板格式");
        }
    }
    /*@ApiOperation("下载模板")
    @PostMapping(value = "/download")
    public Object download(){
        try {
            return FileUtil.downloadFile(SystemConfig.filePath() + "templet"+ File.separator+"patient.xlsx");
        } catch (IOException e) {
            return CommonResult.error(ResultCode.ERROR,"未找到模板文件");
        }
    }*/
    /**
     * @desc 年龄性别检测
     * @author lhl
     * @date 2020-07-01 17:34
     * @param null
     * @return
     */
    /*@RequestMapping(value = "/detectFaces", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult detectFaces(String image) {

        byte[] bytes = Base64Util.base64ToBytes(image);
        ImageInfo rgbData = ImageFactory.getRGBData(bytes);
        List<FaceDetectResDTO> faceDetectResDTOS = Lists.newLinkedList();
        List<FaceInfo> faceInfoList = faceEngineService.detectFaces(rgbData);
        if (CollectionUtil.isNotEmpty(faceInfoList)) {
            List<ProcessInfo> process = faceEngineService.process(rgbData, faceInfoList);

            for (int i = 0; i < faceInfoList.size(); i++) {
                FaceDetectResDTO faceDetectResDTO = new FaceDetectResDTO();
                FaceInfo faceInfo = faceInfoList.get(i);
                faceDetectResDTO.setRect(faceInfo.getRect());
                faceDetectResDTO.setOrient(faceInfo.getOrient());
                faceDetectResDTO.setFaceId(faceInfo.getFaceId());
                if (CollectionUtil.isNotEmpty(process)) {
                    ProcessInfo processInfo = process.get(i);
                    faceDetectResDTO.setAge(processInfo.getAge());
                    faceDetectResDTO.setGender(processInfo.getGender());
                    faceDetectResDTO.setLiveness(processInfo.getLiveness());

                }
                faceDetectResDTOS.add(faceDetectResDTO);

            }
        }

        return CommonResult.success(Response.newSuccessResponse(faceDetectResDTOS));
    }*/
    /**
     * @desc 两图比较
     * @author lhl
     * @date 2020-07-01 17:34
     * @param null
     * @return
     */
   /* @RequestMapping(value = "/compareFaces", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult compareFaces(String image1, String image2) {

        byte[] bytes1 = Base64Util.base64ToBytes(image1);
        byte[] bytes2 = Base64Util.base64ToBytes(image2);
        ImageInfo rgbData1 = ImageFactory.getRGBData(bytes1);
        ImageInfo rgbData2 = ImageFactory.getRGBData(bytes2);

        Float similar = faceEngineService.compareFace(rgbData1, rgbData2);

        return CommonResult.success(Response.newSuccessResponse(similar));
    }
*/
    //初始化注册人脸，注册到本地内存
   /* @PostConstruct
    public void initFace() throws FileNotFoundException {
        Map<String, String> fileMap = Maps.newHashMap();
        //fileMap.put("刘护林","C:\\Users\\Administrator\\Desktop\\zp"+File.separator+"3.jpg");
        for (Integer i = 1; i <10 ; i++) {
            fileMap.put(i.toString(), "用户jpg"+i);
        }
        for (String f : fileMap.keySet()) {
            System.out.println("添加第"+count+"张");
            count++;
            File file = ResourceUtils.getFile("F:\\ai\\star\\jpg" + f + ".jpg");
            ImageInfo rgbData = ImageFactory.getRGBData(file);
            List<FaceInfo> faceInfoList = faceEngineService.detectFaces(rgbData);
            if (CollectionUtil.isNotEmpty(faceInfoList)) {
                byte[] feature = faceEngineService.extractFaceFeature(rgbData, faceInfoList.get(0));
               FileInfo patient = new FileInfo();
                patient.setFileNum(IdUtil.simpleUUID());
                patient.setPatientName(fileMap.get(f));
                patient.setPatientGender(true);
                patient.setFaceFeature(feature);
                 patient.setPatientAge(RandomUtil.randomInt(20,70));
                 patient.setPatientTel("135"+RandomUtil.randomInt(100,999)+"22"+RandomUtil.randomInt(100,999));
                 patient.setPatientIdNum("500235********1017");
                 patient.setHospitalNum(String.valueOf(RandomUtil.randomInt(1,9999)));
                 patient.setAdmissionDate(new Date());
                fileInfoService.save(patient);
            }
        }

    }*/
}
